package com.flycms.modules.user.controller;

import com.flycms.common.controller.BaseController;
import com.flycms.common.exception.ApiAssert;
import com.flycms.common.utils.result.Result;
import com.flycms.modules.shiro.ShiroUtils;
import com.flycms.modules.shiro.UserToken;
import com.flycms.modules.user.entity.RegisterUserVO;
import com.flycms.modules.user.entity.User;
import com.flycms.modules.user.entity.UserRole;
import com.wf.captcha.utils.CaptchaUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * 用户账户相关操作，登录、注册、退出
 *
 * @author 孙开飞
 */
@Controller
@RequestMapping("/member")
public class UserFrontController extends BaseController {

	@GetMapping("/register{url.suffix}")
	public String regUser()
	{
		return "system/member/register";
	}

	/**
	 * ajax提交注册信息
	 */
	@PostMapping(value = "/register{url.suffix}")
	@ResponseBody
	public Object regUser(RegisterUserVO regVo) throws IllegalAccessException {
		if(StringUtils.isEmpty(regVo.getUserName())){
			return failure("用户不能为空");
		}
		if(StringUtils.isEmpty(regVo.getVercode())){
			return failure("短信不能为空");
		}
		if(StringUtils.isEmpty(regVo.getPassword())){
			return failure("用户密码不能为空");
		}
		if(StringUtils.isEmpty(regVo.getRepass())){
			return failure("确认密码不能为空");
		}
		if(!regVo.getPassword().equalsIgnoreCase(regVo.getRepass())){
			return failure("确认密码不正确");
		}
		return userService.addUser(regVo);
	}


	// 发送手机验证码
	@PostMapping("/sms_code{url.suffix}")
	@ResponseBody
	public Object sms_code(String captcha, String mobile, HttpSession session) throws Exception {
		ApiAssert.notTrue( StringUtils.isEmpty(captcha), "请输入验证码");
		if (!CaptchaUtil.ver(captcha, request)) {
			CaptchaUtil.clear(request);  // 清除session中的验证码
			return failure(2,"验证码不正确");
		}
		ApiAssert.notEmpty(mobile, "请输入手机号");
		ApiAssert.isTrue(com.flycms.common.utils.StringUtils.check(mobile, com.flycms.common.utils.StringUtils.MOBILEREGEX), "请输入正确的手机号");
		return userService.regMobileCode(mobile);
	}


	// 登录

	@GetMapping(value = "/login{url.suffix}")
	public String login() {
		return "system/member/login";
	}

	/**
	 * ajax登录
	 */
	@ResponseBody
	@PostMapping(value = "/login{url.suffix}")
	public Result login( @RequestParam(value = "username", required = false)String username,
						 @RequestParam(value = "password", required = false)String password,
						 @RequestParam(value = "captcha", required = false)String captcha,
						 @RequestParam(value = "remember", required = false)boolean remember) throws IllegalAccessException {
		ApiAssert.notTrue( StringUtils.isEmpty(captcha), "请输入验证码");
		if (!CaptchaUtil.ver(captcha, request)) {
			CaptchaUtil.clear(request);  // 清除session中的验证码
			return failure(2,"验证码不正确");
		}
		try{
			Subject subject = ShiroUtils.getSubject();
			UsernamePasswordToken token = new UserToken(username, password);
			subject.login(token);
            return success("您登陆的是管理员账户","/member/index");
		}catch (UnknownAccountException e) {
            return failure("账号不存在");
		}catch (LockedAccountException e) {
            return failure("账号已被锁定,请联系管理员");
		} catch (IncorrectCredentialsException e) {
            return failure("账号或密码不正确");
		}catch (AuthenticationException e) {
            return failure("账户验证失败");
		}
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "/logout{url.suffix}", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:/member/login.do";
	}

	@GetMapping("/user/info{url.suffix}")
	public String info(@RequestParam(value = "name", required = false)String name,Model model)
	{
		User user=userService.findById(ShiroUtils.getLoginUser().getId());
		List<UserRole> roles= userRoleService.selectRoleAll();
		String roleIds=userRoleService.selectUserRolesByUserId(ShiroUtils.getLoginUser().getId());
		model.addAttribute("roleIds",roleIds);
		model.addAttribute("user",user);
		model.addAttribute("roles",roles);
		return "system/member/user/info";
	}

	@GetMapping("/user/password{url.suffix}")
	public String password()
	{
		return "system/member/user/password";
	}

	@PostMapping("/user/password{url.suffix}")
	@ResponseBody
	public Object password(@RequestParam(value = "oldPassword", required = false)String oldPassword,
						   @RequestParam(value = "password", required = false)String password,
						   @RequestParam(value = "repassword", required = false)String repassword) {
		if (org.apache.commons.lang3.StringUtils.isBlank(oldPassword)) {
			return Result.failure("原来密码不能为空");
		} else if (oldPassword.length() < 6 && oldPassword.length() >= 32) {
			return Result.failure("密码最少6个字符，最多32个字符");
		}
		if (org.apache.commons.lang3.StringUtils.isBlank(password)) {
			return Result.failure("新密码不能为空");
		} else if (password.length() < 6 && password.length() >= 32) {
			return Result.failure("密码最少6个字符，最多32个字符");
		}
		if (!repassword.equals(password)) {
			return Result.failure("两次密码必须一样");
		}
		return userService.updatePassword(oldPassword,password);
	}
}
